<template>
	<view class="contain" style="padding-bottom: 150rpx;">
		<form @submit="formSubmit">
			<!--content -->
			<view class="release-contentop">
				<input name="menutitle" placeholder="菜谱名称......" class="release-content-inputtop" value=""
					v-model="menutitle" />
			</view>

			<view class="release-contentoptype">
				<input name="menutitle" placeholder="菜谱类别......" class="release-content-inputtop" disabled="true" />
				<view class="" style="margin-top: 20rpx;">
					<view class="u-page__tag-item" v-for="(item, index) in footstypelist" :key="index">
						<u-tag borderColor='#1cb8a7' :bgColor='item.checked?"#1cb8a7":"#fff"'
							:color='!item.checked?"#1cb8a7":"#fff"' :text="item.name" :plain="!item.checked"
							type="warning" :name="index" @click="changeNowState(item,index)">
						</u-tag>
					</view>
				</view>

				<!-- <graceSelectTags itemWidth="200rpx" :items="footstypelist" type="radio" @change="changeNowState">
					</graceSelectTags> -->
			</view>

			<view class="release-content">
				<editor placeholder="菜谱内容......" style="padding-top: 45rpx;line-height: 1.6em;"
					class="release-content-inputtop" id="content" name="content" @ready="onEditorReady" />
			</view>
			<!-- 图片选择  -->
			<view style="margin-top:20px">
				<view class="food-title">选择图片(最多选择9张)</view>
			</view>
			<view style="margin-top:5rpx;">
				<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
					:maxCount="10"></u-upload>
			</view>

			<view style="position: fixed;bottom: 20px;width: 100%;left: 0;">
				<button formType="submit"  class="btn"
					>发布</button>
			</view>
		</form>
	</view>
</template>

<script>
	// import gracePage from "../../graceUI/components/gracePage.vue";
	// import graceSelectImgAndUpload from "../../graceUI/components/graceSelectImgAndUpload.vue";
	// import graceSelectTags from '../../graceUI/components/graceSelectTags.vue';
	import {
		saveFoods,
		updateFoods,
		infoFoods
	} from "@/api/Foods.js";
	export default {
		data() {
			return {
				textareaVal: '',


				menutitle: "", //美食名称
				menucontent: "", //美食内容
				username: this.$util.getUser().username,
				footstypelist: [],
				footstypeval: "",
				fileList1: [],
				action: this.$config.URL + 'api/app/sysFile/v1/save',
				info:{}
			}
		},
		// components: {
		// 	gracePage,
		// 	graceSelectImgAndUpload,
		// 	graceSelectTags
		// },
		onLoad(op) {
			setTimeout(() => {
				this.defaultItems = [];
			}, 1000)
			this.foodstype();
			console.log('获取id', op.id)
			if (op.id) {
				uni.setNavigationBarTitle({
					title: '编辑餐谱'
				});
				this.editInfo(op.id)
			}

		},
		methods: {
			// 根据id获取
			async editInfo(id) {
				const {
					data
				} = await infoFoods(id)
				if (data.code == 0) {
					this.info=data.data;
					this.menutitle = data.data.foodsTitle;
					this.footstypeval = data.data.foodsType;
					this.footstypelist.forEach((item, index) => {
						if(index==this.footstypeval){
							item.checked=true
						}else{
							item.checked=false
						}
					});
					this.menucontent = data.data.foodsContent;
					if(data.data.foodsImg){
						JSON.parse(data.data.foodsImg).forEach(it=>{
							this.fileList1.push({url:it})
						})
						
						
					}
					console.log('this.footstypeval',this.footstypeval)
					this.onEditorReady()
				}
			},
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1);
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let fileListLen = this[`fileList${event.name}`].length;
				console.log('this.fileList1', this.fileList1)
				console.log('lists', lists)
				lists.map(item => {
					console.log('item', item)
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					});
				});
				console.log('this[`fileList${event.name}`]', this[`fileList${event.name}`])
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url);

					let item = this[`fileList${event.name}`][fileListLen];
					this[`fileList${event.name}`].splice(
						fileListLen,
						1,
						Object.assign(item, {
							status: 'success',
							message: '',
							url: result
						})
					);
					fileListLen++;
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: this.action, // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						formData: {
							user: 'test'
						},
						success: res => {
							resolve(JSON.parse(res.data).url)

						}
					});
				});
			},
			onEditorReady() {
				uni.createSelectorQuery().select("#content").context((res) => {
					this.editorCtx = res.context;
					if (this.menucontent) {
						this.editorCtx.setContents({
							html: this.menucontent,
							success: (res) => {
								console.log("success", res)
							},
							fail: (res) => {
								console.log("fail", res)
							},
						})
					}

				}).exec();
			},


			// 提交动态
			// submit: function() {
			// 	if (this.selectedimgs.length < 1) {
			// 		uni.showToast({
			// 			title: "请选择图片",
			// 			icon: "none"
			// 		});
			// 		return;
			// 	}
			// 	this.$refs.selectimgandupload.upload();
			// },
			//上传成功
			imgLoaded: function(res) {
				let that = this;
				let imgsRes = res;
				that.selectedimgs = [];
				imgsRes.forEach(function(item, index) {
					that.selectedimgs.push(item.result.url);
				});
			},

			// 提交动态
			formSubmit() {

				var submit = (content) => {
					if (content.html == "") {
						return uni.showToast({
							title: "内容不能为空",
							icon: "none"
						})
					}
					if (this.menutitle == "") {
						return uni.showToast({
							title: "名称不能为空",
							icon: "none"
						})
					}
					if (this.fileList1.length < 1) {
						uni.showToast({
							title: "请选择图片",
							icon: "none",
						});
						return;
					}
					uni.showLoading({
						title: "正在发布中...",
						mask: true
					})
					if(this.info.id){
						this.info.foodsContent=content.html;
						this.info.foodsTitle=this.menutitle;
						this.info.foodsDetail=content.text;
						this.info.foodsImg=JSON.stringify(this.fileList1.map(it => it.url));
						this.info.foodsType=this.footstypeval ? this.footstypeval : this.footstypelist[0].value;
						
						updateFoods(this.info).then(
							res => {
								uni.hideLoading()
								if (res.data.code == "0") {
									this.$api.showTip("编辑成功", () => {
										uni.navigateBack({
											delta: 1
										});
									});
								} else {
									this.$api.showTip(res.data.msg);
								}
							},
							err => {
								uni.hideLoading();
								this.$api.showTip('服务器错误');
							}
						);
					}else{
						var data = {
								foodsAuthor: this.username,
								foodsContent: content.html,
								foodsTitle: this.menutitle,
								createTime: "",
								delFlag: "",
								disFlag: "",
								foodsAuthorId: "",
								foodsCheckPerson: "",
								foodsCopyPeople: "",
								foodsDetail: content.text,
								foodsImg: JSON.stringify(this.fileList1.map(it => it.url)),
								foodsLevel: "",
								foodsState: "",
								foodsTime: "",
								foodsType: this.footstypeval ? this.footstypeval : this.footstypelist[0].value,
							}
							console.log('获取参数', data, this.footstypeval)
							saveFoods(data).then(
								res => {
									uni.hideLoading()
									if (res.data.code == "0") {
										this.$api.showTip("发布成功", () => {
											uni.navigateBack({
												delta: 1
											});
										});
									} else {
										this.$api.showTip(res.data.msg);
									}
								},
								err => {
									uni.hideLoading();
									this.$api.showTip('服务器错误');
								}
							);
						}
					}
					
				this.editorCtx.getContents({
					success: (res) => {
						submit(res);
					}
				})
			},
			foodstype() {
				let foodtypelist = this.$util.getdictionary('餐类')
				console.log('获取类wwwwwwwwwww型', foodtypelist)
				foodtypelist.forEach((item, index) => {
					this.footstypelist.push({
						name: item.name,
						value: item.value,
						checked: false
					});
				});
				console.log('获取类型', this.footstypelist)
				//判断是否有数据
				if (this.footstypelist[0]) {
					// 第一个默认true
					this.footstypelist[0].checked = true;
					// that.demoVal = "";
				}
			},
			// 点选按钮
			changeNowState(it, i) {
				this.footstypeval = i;
				this.footstypelist.map((itm, index) => {
					if (i == index) {
						console.log('sssssssssssssss', index)
						itm.checked = true
					} else {
						itm.checked = false
					}
					return it
				})
				// this.getData(this.params)
				this.show = false
			},

		}

	}
</script>

<style scoped lang="scss">
	.contain {
		padding: 0 24rpx;
	}

	.u-page__tag-item {
		display: inline-block;
		margin-right: 30rpx;
		margin-left: 30rpx;
		margin-bottom: 20rpx;
	}

	.release-contentop {
		margin-top: 20rpx;
		background-color: #FFFFFF;
		border-radius: 10rpx;
		height: 100rpx;
	}

	.release-contentoptype {
		margin-top: 20rpx;
		background-color: #FFFFFF;
		border-radius: 10rpx;
		padding-bottom: 10rpx;
	}

	.release-content-inputtop {
		height: 100rpx;
		font-size: 28rpx;
		width: 650;
		color: #8e8080;
		padding: 0 25rpx;
		line-height: 26rpx;
	}

	.release-content {
		margin-top: 40rpx;
		background-color: #FFFFFF;
		border-radius: 10rpx;
	}

	.release-button {
		background: #3688FF;
		height: 50rpx;
		padding: 0 25rpx;
		line-height: 50rpx;
		border-radius: 50rpx;
		color: #FFFFFF;
		font-size: 22rpx;
	}

	.release-content-input {
		height: 180rpx;
		font-size: 28rpx;
		width: 650;
		color: #8e8080;
		padding: 25rpx;
		line-height: 46rpx;
	}

	.food-title {
		font-size: 30rpx;
		font-weight: bold;
		color: rgba(0, 0, 0, 0.8);
		opacity: 1;
	}

	/deep/ .u-upload__button {
		width: 120px !important;
		height: 120px !important;
		background-color: #fff!important;
		margin-top: 20rpx!important;
	}
</style>